<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Topic extends CI_Controller {
	
	private $status;
	
	/**
	 * __construct function
	 * construct function containing the insert and view of topic
	 */
	function __construct() {
		parent::__construct();
		$this->load->library('ion_auth');
		$this->load->library('form_validation');
		$this->load->helper(array('form', 'url'));
		$this->load->model('common_model');

		$this->load->database();

		$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));

		$this->load->helper('language');
	}

	public function addatopicform() {
		if (!$this->ion_auth->logged_in()) {
			redirect('login', 'refresh');
		}
		$user = $this->ion_auth->user()->row();
		$this->data['user_id'] = $user->id;

		$this->topics = array(
	            'topic_title' 		=> $this->input->post('topic_title', true),
	            'topic_tags' 		=> $this->input->post('tags', true),
	            'short_description' => $this->input->post('short_description', true),
	            'random_code' 		=> $this->input->post('random_code', true),
	            'posting_date' 		=> $this->input->post('posting_date', true),
	            'isActive' 			=> $this->input->post('isActive', true),
	            'user_id' 			=> $this->input->post('user_id', true)
		);

		$this->choices = array(
			'random_code' 	=> $this->input->post('random_code', true),
			'choice_one' 	=> $this->input->post('choice_1', true),
            'choice_two' 	=> $this->input->post('choice_2', true),
            'choice_three' 	=> $this->input->post('choice_3', true),
            'choice_four' 	=> $this->input->post('choice_4', true),
            'choice_five' 	=> $this->input->post('choice_5', true)
		);
		
		$config = array(
			array (
				'field' => 'topic_title', 
				'label' => 'Topic Title', 
				'rules' => 'trim|required|xss_clean'
			)
		);

		$this->form_validation->set_rules($config);

		if ($this->form_validation->run() === FALSE) {
			/* Return validation error */
			$this->_status['status'] = 0;
			$this->_status['msg'] = validation_errors();
		} else {
			$this->results = $this->common_model->insertRecords($this->common_model->_topicsTable, $this->topics);
			$this->results = $this->common_model->insertRecords($this->common_model->_adminChoicesTable, $this->choices);

			if ($this->results) {
				$this->status['msg'] = "Topic successfully added";
			} else {
				$this->status['msg'] = "Offffffffff! You did wrong";
			}
		}
		echo json_encode($this->status);
		
		$this->data['title'] = "Add new topic";
		$this->data['subtitle'] = 'Latest topic will show in recent topics and homepage';

		$this->load->view('layout/header', $this->data);
		$this->load->view('newtopic', $this->data);
		$this->load->view('layout/footer');
	}
	
}
?>